package com.sjms._12_行为_代理模式._3_Cglib代理;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 代理类
 */
public class Son implements MethodInterceptor {

    //被代理对象
    private Object object;

    //设置被代理对象
    public void setTarget(Object object) {
        this.object = object;
    }

    //创建并返回代理对象
    public Object getProxy() {
        //创建类、指定父类、指定回调
        return Enhancer.create(object.getClass(), this);
    }

    /**
     * 代理方法执行时的回调
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        //前置
        System.out.println("儿子：爸爸我去吧，我出门啦！！！");

        //执行原始方法
        Object invoke = method.invoke(object, objects);

        System.out.println("爸爸：" + invoke);

        //后置
        System.out.println("儿子：爸爸，我回来了");

        return "【肉x500g】【辣椒x100g】【洗涤剂x500ml】【煊赫门x2盒】";
    }
}
